﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lincolnwood.Foundation.Common.Data;
using Lincolnwood.Foundation.SermonLibrary.Data;

namespace Lincolnwood.Foundation.SermonLibrary
{
    public class SermonLibraryService
    {
        private IUnitOfWork _unitOfWork;
        private ISermonRepository _sermonRepository;
        private ISermonSeriesRepository _sermonSeriesRepository;

        public SermonLibraryService(IUnitOfWork unitOfWork, ISermonRepository repository, ISermonSeriesRepository sermonSeriesRepository)
        {
            _unitOfWork = unitOfWork;
            _sermonRepository = repository;
            _sermonSeriesRepository = sermonSeriesRepository;
        }

        public Sermon CreateSermon(Sermon sermon)
        {
            Sermon clonedInput = Cloner.Clone<Sermon>(sermon);

            // persist
            var result = _sermonRepository.Add(clonedInput);
            _unitOfWork.Flush();

            var clonedOutput = Cloner.Clone<Sermon>(result);

            return clonedOutput;
        }

        public void RemoveSermon(Guid sermonId)
        {
            _sermonRepository.RemoveById(sermonId);
            _unitOfWork.Flush();
        }

        public Sermon ModifySermon(Sermon sermon)
        {
            Sermon clonedInput = Cloner.Clone<Sermon>(sermon);

            // persist
            _sermonRepository.Merge(clonedInput);
            _unitOfWork.Flush();

            var clonedOutput = Cloner.Clone<Sermon>(clonedInput);

            return clonedOutput;

        }

        public Sermon GetSermonById(Guid sermonId)
        {
            var result =  _sermonRepository.FindById(sermonId);
            return Cloner.Clone<Sermon>(result);
        }

        public IEnumerable<Sermon> GetSermonsPaged(int pageIndex, int itemsPerPage, PublishedStatus publishedStatus)
        {
            var result =  _sermonRepository.GetSermonsPaged(pageIndex, itemsPerPage, publishedStatus);
            return Cloner.Clone<Sermon>(result);
        }

        public IEnumerable<Sermon> GetSermonsInSeries(Guid sermonSeriesId)
        {
            var result = _sermonRepository.GetSermonsInSeries(sermonSeriesId);
            return Cloner.Clone<Sermon>(result);
        }

        public IEnumerable<SermonSeries> GetAllSeries()
        {
            var result = _sermonSeriesRepository.All();
            return Cloner.Clone<SermonSeries>(result);
        }

        public IEnumerable<SermonSeries> GetAllSeriesPaged(int pageIndex, int itemsPerPage)
        {
            var result = _sermonSeriesRepository.GetSermonsSeriesPaged(pageIndex, itemsPerPage);
            return Cloner.Clone<SermonSeries>(result);
        }
    }
}